using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using System.Linq;

public class SaveManager : MonoBehaviour
{
    public static SaveManager instance;

    [SerializeField] public string fileName;

    public GameData gameData;
    private List<ISaveManager> saveManagers;
    private FileDataHandler dataHandler;
    public bool encryptData;

    [ContextMenu("Delete Save File")]
    private void DeleteSaveData()
    {
        dataHandler = new FileDataHandler(Application.persistentDataPath, fileName, encryptData);
        dataHandler.Delete();
    }

    private void Awake()
    {
        if (instance != null)       //����Ѿ�����ʵ����������������ǰ���󣬲�����ʵ��������
        {
            Destroy(instance.gameObject);
            instance = this;
        }
        else instance = this;
    }

    private void Start()
    {
        dataHandler = new FileDataHandler(Application.persistentDataPath, fileName, encryptData);
        saveManagers = FindAllSaveManager();

        LoadGame();                                                             ///************************************
    }

    public void NewGame()
    {
        gameData = new GameData();
    }

    public void LoadGame()
    {
        gameData = dataHandler.Load();

        if(this.gameData == null)
        {
            NewGame();
        }

        foreach(ISaveManager saveManager in saveManagers) 
        {
            saveManager.LoadData(gameData);                                             ///************************************
        }
    }

    public void SaveGame() 
    {
        foreach(ISaveManager saveManager in saveManagers) 
        {
            saveManager.SaveData(ref gameData);
        }

        dataHandler.Save(gameData);
    }

    private void OnApplicationQuit()
    {
        SaveGame();
    }

    private List<ISaveManager> FindAllSaveManager() 
    {
        IEnumerable<ISaveManager> saveManagers = FindObjectsOfType<MonoBehaviour>(true).OfType<ISaveManager>();

        return new List<ISaveManager>(saveManagers);
    }

    public bool HasSaveData()
    {
        if (dataHandler.Load() != null)
            return true;

        return false;
    }
}
